// 历史交易量监控页面主逻辑

/**
 * 历史交易量监控应用主类
 */
class HistoryMonitorApp {
    constructor() {
        this.config = {
            refreshInterval: 5 * 60 * 1000, // 5分钟刷新
            apiEndpoint: '/api/tranvolume/history/statistics'
        };
        
        this.timer = null;
        this.isUsingMockData = true;
        this.mockData = this.initMockData();
        
        this.init();
    }

    /**
     * 初始化应用
     */
    async init() {
        try {
            showLoading(true);
            
            // 初始化时间显示
            this.initTimeDisplay();
            
            // 初始化事件监听
            this.initEventListeners();
            
            // 检查API可用性
            await this.checkApiAvailability();
            
            // 加载初始数据
            await this.loadHistoryData();
            
            // 启动定时刷新
            this.startAutoRefresh();
            
            showLoading(false);
            updateStatus('success', '系统运行正常');
            
            log('info', '历史交易量监控系统初始化完成');
        } catch (error) {
            handleError(error, '系统初始化');
            showLoading(false);
        }
    }

    /**
     * 初始化模拟数据
     */
    initMockData() {
        return {
            hourly: this.generateHistoryData('hour', 24),
            daily: this.generateHistoryData('day', 30),
            weekly: this.generateHistoryData('week', 12),
            monthly: this.generateHistoryData('month', 12)
        };
    }

    /**
     * 生成历史数据
     */
    generateHistoryData(dimension, count) {
        const data = [];
        const now = new Date();
        let interval, format;

        switch (dimension) {
            case 'hour':
                interval = 3600000; // 1小时
                format = { hour: '2-digit', day: '2-digit' };
                break;
            case 'day':
                interval = 24 * 3600000; // 1天
                format = { month: '2-digit', day: '2-digit' };
                break;
            case 'week':
                interval = 7 * 24 * 3600000; // 1周
                format = { month: '2-digit', day: '2-digit' };
                break;
            case 'month':
                interval = 30 * 24 * 3600000; // 1月
                format = { year: 'numeric', month: '2-digit' };
                break;
        }

        // 生成当期数据
        for (let i = count - 1; i >= 0; i--) {
            const time = new Date(now.getTime() - i * interval);
            const timeStr = time.toLocaleDateString('zh-CN', format);
            
            const baseVolume = dimension === 'hour' ? 2000 : 
                              dimension === 'day' ? 45000 : 
                              dimension === 'week' ? 300000 : 1200000;
            
            const volume = Math.floor(baseVolume * (0.8 + Math.random() * 0.4));
            const successRate = 92 + Math.random() * 7; // 92%-99%之间
            
            data.push({
                time: timeStr,
                totalVolume: volume,
                successVolume: Math.floor(volume * successRate / 100),
                failVolume: Math.floor(volume * (100 - successRate) / 100)
            });
        }

        return {
            current: data,
            updateTime: new Date().toLocaleString('zh-CN')
        };
    }

    /**
     * 初始化时间显示
     */
    initTimeDisplay() {
        const updateTime = () => {
            $('#currentTime').text(getCurrentTimeString());
        };
        
        updateTime();
        setInterval(updateTime, 1000);
    }

    /**
     * 初始化事件监听
     */
    initEventListeners() {
        // 查询条件变化时重新加载数据
        $('#statisticDimension').on('change', debounce(async (e) => {
            await this.loadHistoryData();
        }, 300));

        $('#historyTimeRange').on('change', debounce(async (e) => {
            await this.loadHistoryData();
        }, 300));

        $('#historyCenterSelect').on('change', debounce(async (e) => {
            await this.loadHistoryData();
        }, 300));

        $('#historyServicePlatSelect').on('change', debounce(async (e) => {
            await this.loadHistoryData();
        }, 300));

        $('#historyChelCodeSelect').on('change', debounce(async (e) => {
            await this.loadHistoryData();
        }, 300));

        // 页面可见性变化处理
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.pauseAutoRefresh();
            } else {
                this.resumeAutoRefresh();
            }
        });
    }

    /**
     * 检查API可用性
     */
    async checkApiAvailability() {
        try {
            const response = await $.ajax({
                url: '/api/tranvolume/health',
                method: 'GET',
                timeout: 3000
            });
            
            if (response && response.success) {
                this.isUsingMockData = false;
                log('info', 'API服务可用，使用真实数据');
                updateStatus('success', 'API连接正常');
            } else {
                throw new Error('API响应异常');
            }
        } catch (error) {
            this.isUsingMockData = true;
            log('warn', 'API服务不可用，使用模拟数据', error);
            updateStatus('error', '使用模拟数据');
        }
    }

    /**
     * 加载历史交易量数据
     */
    async loadHistoryData() {
        try {
            const dimension = $('#statisticDimension').val() || 'day';
            const timeRange = parseInt($('#historyTimeRange').val()) || 720;
            const center = $('#historyCenterSelect').val();
            const servicePlat = $('#historyServicePlatSelect').val();
            const chelCode = $('#historyChelCodeSelect').val();
            
            let data;
            
            if (this.isUsingMockData) {
                // 根据参数动态生成数据
                const count = this.getDataCount(dimension, timeRange);
                data = this.generateHistoryData(dimension, count);
            } else {
                const params = { 
                    dimension, 
                    timeRange, 
                    center, 
                    servicePlat, 
                    chelCode 
                };
                const response = await $.ajax({
                    url: this.config.apiEndpoint,
                    method: 'GET',
                    data: params,
                    timeout: 10000
                });
                data = response.data;
            }

            // 创建历史趋势图表
            createHistoryTrendChart('historyChart', data, 'none');
            
            // 更新统计卡片
            this.updateStatCards(data);

            log('info', '历史交易量数据更新完成');
        } catch (error) {
            handleError(error, '历史交易量数据加载');
        }
    }

    /**
     * 根据维度和时间范围计算数据点数量
     */
    getDataCount(dimension, timeRange) {
        switch (dimension) {
            case 'hour':
                return Math.min(timeRange, 168); // 最多7天
            case 'day':
                return Math.min(Math.floor(timeRange / 24), 90); // 最多90天
            case 'week':
                return Math.min(Math.floor(timeRange / 168), 26); // 最多26周
            case 'month':
                return Math.min(Math.floor(timeRange / 720), 24); // 最多24月
            default:
                return 30;
        }
    }

    /**
     * 更新统计卡片
     */
    updateStatCards(data) {
        const currentData = data.current || [];
        
        if (currentData.length === 0) return;

        // 计算统计指标
        const totalVolume = currentData.reduce((sum, item) => sum + item.totalVolume, 0);
        const peakVolume = Math.max(...currentData.map(item => item.totalVolume));
        const avgVolume = totalVolume / currentData.length;

        // 更新UI
        $('#totalHistoryVolume').text(formatNumber(totalVolume));
        $('#peakHistoryVolume').text(formatNumber(peakVolume));
        $('#avgHistoryVolume').text(formatNumber(Math.floor(avgVolume)));
    }

    /**
     * 启动自动刷新
     */
    startAutoRefresh() {
        this.timer = setInterval(() => {
            this.loadHistoryData();
        }, this.config.refreshInterval);
        
        log('info', '历史交易量监控自动刷新已启动');
    }

    /**
     * 暂停自动刷新
     */
    pauseAutoRefresh() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
        log('info', '历史交易量监控自动刷新已暂停');
    }

    /**
     * 恢复自动刷新
     */
    resumeAutoRefresh() {
        if (!this.timer) {
            this.startAutoRefresh();
            log('info', '历史交易量监控自动刷新已恢复');
        }
    }

    /**
     * 销毁应用
     */
    destroy() {
        this.pauseAutoRefresh();
        chartManager.disposeAll();
        log('info', '历史交易量监控应用已销毁');
    }
}

// 全局历史监控应用实例
let historyMonitorApp;

// 文档加载完成后初始化应用
$(document).ready(function() {
    historyMonitorApp = new HistoryMonitorApp();
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    if (historyMonitorApp) {
        historyMonitorApp.destroy();
    }
});